package com.helloniu.wb.tools {

import com.helloniu.wb.containers.ShapeTypeDef;
import com.helloniu.data.wb.TextStyle;
import com.helloniu.fl.util.Tool;
import flash.display.Graphics;
import flash.events.Event;
import flash.events.FocusEvent;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.events.TextEvent;
import flash.geom.Rectangle;
import flash.text.TextFieldAutoSize;
import flash.text.TextFieldType;
import flash.ui.Keyboard;
import mx.core.UITextField;

public class TextTool extends RectangularTool {
    private var textField:UITextField;
    private var content:String = "default text";

    public function TextTool() {
        super();

        textField = new UITextField();
        textField.autoSize = TextFieldAutoSize.NONE;
        textField.doubleClickEnabled = false;
        textField.mouseEnabled = false; // cannot edit now
        textField.wordWrap  = true;
        textField.selectable = true;

        textField.text = content;
        
        this.setWBStyle(new TextStyle(), false);        
        this.setShapeType(ShapeTypeDef.TEXT);
    }

    override public function mouseDownHandler(event:MouseEvent):void {
        super.mouseDownHandler(event);

        if(!isPainting()) {
            startEditing(null);
        }
    }

    public function setText(content0:String):void {
        this.content = content0;

        if(textField != null) {
            textField.text = content;
        }
    }

    public function clear():void {
        //graphics.clear();
        //textField = null;
        //content = null;
    }

    private function doubleClickFunc(event:MouseEvent):void {
        startEditing(null);
    }

    override protected function createChildren():void {
        super.createChildren();

        textField.addEventListener(FocusEvent.FOCUS_OUT, stopEditing, false, 0,
                                   true);
        textField.addEventListener(KeyboardEvent.KEY_UP, keyUp, false, 0,
                                   true);
        textField.addEventListener(KeyboardEvent.KEY_DOWN, keyDown, false, 0,
                                   true);
        textField.addEventListener(Event.CHANGE, textChanged, false, 0,
                                   true);

        textField.addEventListener(TextEvent.TEXT_INPUT, textInput, false, 0,
                                   true);
        addChild(textField);
    }

    private function stopEditing(event:*):void {
        if(textField == null) { // destroyed
            return;
        }

        stage.removeEventListener(MouseEvent.MOUSE_DOWN, stageMouseDown);

        if(textField.type == TextFieldType.INPUT) {
            if((textField.text + "") != (content + "")) {
                Tool.traceT("------stopEditing------: " + textField.text +"|"+ content);
                // @temp tonyy, event
                // fire ModifyEvent
            }

            textField.type = TextFieldType.DYNAMIC;
            textField.selectable = true;
            textField.setSelection(0, 0);
            textField.scrollH = 0;
            content = textField.text;
        }
    }

    private function keyUp(event:KeyboardEvent):void {
        if(event.keyCode == Keyboard.ENTER) {
            //GUIHelper.trace("--: key down:" + textField.textHeight +"|"+ textField.height);
            var idx:int = textField.caretIndex;
            var str:String  = textField.text;

            textField.text = str.substr(0, idx) + "\n" + str.substr(idx);
            textField.setSelection(idx + 1, idx + 1);

            if(textField.textHeight + 22 > textField.height) {
                //textField.height = textField.height + 22;
                addEndXY(0, 22);
                repaint();
            }

        }
    }

    private function keyDown(event:KeyboardEvent):void {
    }

    private function textChanged(event:Event):void {
    }

    private function textInput(event:TextEvent):void {
    }

    public function isEditing():Boolean {
        return textField != null && textField.type == TextFieldType.INPUT;
    }

    public function startEditing(listener:Object = null):void {
        if(isEditing()) {
            return;
        }

        //editListener = listener;
        textField.type = TextFieldType.INPUT;
        textField.text = content;
        textField.setFocus();
        textField.setSelection(0, textField.text.length);
        stage.addEventListener(MouseEvent.MOUSE_DOWN, stageMouseDown, false, 0,
                               true);
    }

    private function isMouseIn():Boolean {
        return this.mouseX > 0 && this.mouseY > 0 && this.mouseX < this.unscaledWidth &&
            this.mouseY < this.unscaledHeight;
    }

    private function stageMouseDown(event:Event):void {
        if(!isMouseIn()) {
            stopEditing(event);
        }
    }

    override protected function updateResizeHandle():void {
    	var rect:Rectangle = calculateRect();
    	        
        if(rect.width == 0 || rect.height == 0) {
            rect.width = 250;
            rect.height = 100;
        }

        super.updateResizeHandle();
    }

    override protected function drawRectangularShape():void {
        if(textField == null) {
            return;
        }

		if(getCurrWBStyle() is TextStyle) {
			setWBStyle(getCurrWBStyle());
		}

		// @temp tonyy
		var contentStr:String = (getWBStyle() as TextStyle).content;
        var rect:Rectangle = calculateRect();
        
        graphics.clear();
        graphics.lineStyle(0.5, 0x000000, 1);
        graphics.beginFill(0xFFFFFF,.5);
        graphics.moveTo(rect.x, rect.y);
        graphics.drawRect(rect.x, rect.y, rect.width, rect.height);
        graphics.endFill();

        textField.move(rect.x, rect.y);
        textField.textColor = 0; // restore to black
        textField.width = rect.width;
        textField.height = rect.height;
        textField.text = contentStr;
    }
}
}